package com.jinbei.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jinbei.common.contants.Contants;
import com.jinbei.common.util.MD5Util;
import com.jinbei.domain.User;
import com.jinbei.mapper.UserMapper;
import com.jinbei.service.UserService;
import com.jinbei.task.CacheRunner;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


/**
 * Created by zflu on 2018/7/8.
 */
@Service
public class UserServiceImpl implements UserService {

    private final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserMapper userMapper;

    /**
     * @author zflu
     * @Description   根据用户id查询User
     * @date 2018/7/9 13:57
     * @param userId
     * @return com.jinbei.domain.User
     */
    @Override
    public User queryUserByUserId(int userId) throws Exception {
        User user = userMapper.queryUserByUserId(userId);
        if(user != null){
            user.setPassword(null);
        }
        return user;
    }

    /**
     * @author zflu
     * @Description   根据用户id删除User
     * @date 2018/7/9 14:01
     * @param userId
     * @return int
     */
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public int deleteUserByUserId(int userId) throws Exception {
        return userMapper.deleteUserByUserId(userId);
    }

    /**
     * @author zflu
     * @Description   新增用户
     * @date 2018/7/9 14:04
     * @param user
     * @return int
     */
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public int insertUser(User user) throws Exception {
        //Md5加密
        user.setPassword(MD5Util.MD5(user.getPassword()));
        //初始化状态
        user.setStatus(Contants.INIT_ROLE);
        user.setDeleteStatus(Contants.ZERO);
        //2为普通用户
        user.setRoles("1");
        return userMapper.insertUser(user);
    }

    /**
     * @author zflu
     * @Description   更新用户
     * @date 2018/7/9 14:08
     * @param user
     * @return int
     */
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public int updateUser(User user) throws Exception {
        String password = user.getPassword();
        if(StringUtils.isNotBlank(password)){
            //MD5加密
            user.setPassword(MD5Util.MD5(password));
        }
        return userMapper.updateUser(user);
    }

    /**
     * @author zflu
     * @Description 查询被锁定的用户
     * @date 2018/7/9 14:11
     * @return java.util.Map
     */
    @Override
    public Map queryUserByLock() throws Exception{
        //获取所有被锁定的用户id
        List<Integer> result = userMapper.queryUserByLock();
        Map<String,Integer> map = new HashMap<>(result.size());
        for (Integer info: result) {
            String key = String.valueOf(info);
            map.put(key,info);
        }
        return map;
    }

    /**
     * @author zflu
     * @Description 解锁或者上锁用户
     * @date 2018/7/9 14:36
     * @param userId
     * @return int
     */
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public int lockOrUnLockUser(int userId) throws Exception {
        int result;
        Integer cacheUser = CacheRunner.cacheMap.get(String.valueOf(userId));
        String key = String.valueOf(userId);
        //如果查询缓存，改用户没有锁
        if(cacheUser == null){
            //添加锁
            CacheRunner.cacheMap.put(key,userId);
            //修改数据库 上锁
            result = userMapper.lockOrUnLockUser(userId,Contants.LOCK_USER);
        }else{
            //移除锁
            CacheRunner.cacheMap.remove(key);
            //修改数据库 解锁
            result = userMapper.lockOrUnLockUser(userId,Contants.INIT_ROLE);
        }
        return result;
    }

    /**
     * @author zflu
     * @Description   登录验证账号密码是否正确
     * @date 2018/7/10 10:42
     * @param loginName, password
     * @return com.jinbei.domain.User
     */
    @Override
    public User queryLoginUser(String loginName, String password) throws Exception {
        return userMapper.queryLoginUser(loginName,MD5Util.MD5(password));
    }

    /**
     * @author zflu
     * @Description   根据用户id查询授权接口
     * @date 2018/7/10 13:33
     * @param userId
     * @return java.lang.String
     */
    @Override
    public HashSet<String> queryUserAuthorUrl(int userId) throws Exception {
        HashSet<String> hashSet = new HashSet<>();
        String url = userMapper.queryUserAuthorUrl(userId);
        if(StringUtils.isNotBlank(url)){
            //空间换时间
            String[] split = url.split(",");
            List<String> list = Arrays.asList(split);
            hashSet.addAll(list);
        }
        return hashSet;
    }

    /**
     * @author zflu
     * @Description   用户分页列表
     * @date 2018/7/11 17:03
     * @param pageNum, pageSize
     * @return com.github.pagehelper.Page<com.jinbei.domain.User>
     */
    @Override
    public PageInfo queryUserPage(int pageNum, int pageSize) throws Exception {
        PageHelper.startPage(pageNum,pageSize);
        List<User> users = userMapper.queryUserPage();
        return new PageInfo(users);
    }

    /**
     * @author zflu
     * @Description   根据用户名称查询用户
     * @date 2018/7/19 9:45
     * @param loginName
     * @return com.jinbei.domain.User
     */
    @Override
    public User queryUserByLoginName(String loginName) throws Exception {
        User user = userMapper.queryUserByLoginName(loginName);
        return user;
    }

    /**
     * @author zflu
     * @Description   修改用户密码
     * @date 2018/8/3 11:17
     * @param map
     * @return int
     */
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public int updateUserPassword(Map<String, String> map) throws Exception {
        String loginName = map.get("loginName");
        String password = map.get("password");
        String newPassword = map.get("newPassword");
        if(StringUtils.isNotBlank(loginName)
                && StringUtils.isNotBlank(password)
                && StringUtils.isNotBlank(newPassword)){
            password = MD5Util.MD5(password);
            newPassword = MD5Util.MD5(newPassword);
        }
        int result = userMapper.updateUserPassword(loginName,password,newPassword);
        return result;
    }

    /**
     * @author zflu
     * @Description
     * @date 2018/8/7 13:24
     * @param map
     * @return int
     */
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public int updateUserRoles(Map<String, String> map) throws Exception {
        String userId = map.get("userId");
        String roles = map.get("roles");
        int result = userMapper.updateUserRoles(roles, userId);
        return result;
    }

    /**
     * @author zflu
     * @Description   根据部门id查询用户
     * @date 2018/8/9 13:52
     * @param id
     * @return java.util.List<com.jinbei.domain.User>
     */
    @Override
    public List<User> queryUserListByDeptId(Integer id) throws Exception {
        return userMapper.queryUserListByDeptId(id);
    }

}
